<?php

namespace app\api\controller;

use app\admin\model\money\Change;
use app\admin\model\user\Finance;
use app\admin\model\Withdrawal;
use app\common\controller\Api;
use app\common\model\Config;
use think\Db;
use think\Request;


class Withdraw extends Api
{
    private static $model;
    protected $noNeedRight = '*';


    public function __construct()
    {
        parent::__construct();
        self::$model = new Withdrawal();
    }

    /**
     * 提现类型
     */
    public function wdInfo()
    {
        $id = $this->auth->id;
        $types = \app\common\model\Config::field('type,value')->where('name', 'pay_types')->find();
        $types_arr = explode(',', $types->value);
        $info = [];

        if (in_array('person', $types_arr)) {
            $bankinfo = \app\admin\model\user\Banks::where('type', 1)->where('user_id', $id)->where('status', 1)->find();
            if ($bankinfo) {
                $arr1 = [
                    'reamrk' => 'person',
                    'name' => $bankinfo->bankname,
                    'number' => $bankinfo->banknumber
                ];

                array_push($info, $arr1);
            }
        }
        if (in_array('company', $types_arr)) {
            $bankinfo = \app\admin\model\user\Banks::where('type', 2)->where('user_id', $id)->where('status', 2)->find();
            if ($bankinfo) {
                $arr2 = [
                    'reamrk' => 'company',
                    'name' => $bankinfo->bankname,
                    'number' => $bankinfo->banknumber
                ];

                array_push($info, $arr2);
            }
        }
        if (in_array('wechat', $types_arr)) {
            $account = $this->auth->getUser()->wechat_info;
            if ($account) {
                $arr3 = [
                    'reamrk' => 'wechat',
                    'name' => '微信',
                    'number' => $account
                ];

                array_push($info, $arr3);
            }
        }
        if (in_array('alipay', $types_arr)) {
            $alipay_info = $this->auth->getUser()->alipay_info;
            if ($alipay_info) {
                $alipay_info = json_decode($alipay_info, true);
                $arr4 = [
                    'reamrk' => 'alipay',
                    'name' => '支付宝',
                    'number' => $alipay_info['account']
                ];

                array_push($info, $arr4);
            }
        }

        if (!$info) {
            $this->error('尚未设置收款方式！');
        }

        $this->success('收款方式为', $info);
    }

    /**
     * 提现记录
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $pageSize = input('page_size', 15);
        $moneyType = input('moneytype', 3);
        if (!in_array($moneyType, [3, 4, 5])) {
            $this->error('参数非法！');
        }
        $userId = $this->auth->id;

        $where = [
            'user_id' => $userId,
            'moneytype' => $moneyType
        ];
        $lists = self::$model->field('id,order_num,money,createtime,account_info,status')->where($where)->order('createtime desc')->paginate($pageSize);

        if ($lists) {
            foreach ($lists as $val) {
                if ($val->account_info) {
                    $account_arr = json_decode($val->account_info, true);
                    $account = array_shift($account_arr);
                    $val->account_info = $account;
                }

                $val->createtime = date('Y年m月d日 H:i', $val->createtime);
            }
        }

        $this->success('提现记录', $lists);
    }

    /**
     * 余额提现
     */
    public function create()
    {
        $money = input('money');
        if (!$money || $money <= 0) {
            $this->error('必须输入正确提现金额！');
        }

        $late_time = strtotime('today') + 16 * 60 * 60;
        if (time() > $late_time) {
            $this->error('超过最晚打款时间！');
        }

        $wd_min_money = config('site.wd_min_money');
        if ($money < $wd_min_money) {
            $this->error('起提额度为' . $wd_min_money);
        }

        $userId = $this->auth->id;
        $today = strtotime('today');
        $wdinfo = Withdrawal::where('user_id', $userId)->where('status', '>=', 0)->where('createtime', '>=', $today)->find();
        if ($wdinfo) {
            $this->error('今天已提现过！');
        }

        $remark = input('remark');
        // 3为静态钱包，4为动态钱包，5为储存钱包
        $moneytype = input('moneytype', 3);
        switch ($moneytype) {
            case 3:
                $field = 'hasmoneys';
                $msg = '静态现金';
                break;
            case 4:
                $field = 'hasmoneyd';
                $msg = '动态现金';
                break;
            case 5:
                $field = 'hasmoney';
                $msg = '储存币';
                break;
            default:
                $this->error('参数错误！');
                break;
        }

        $user = $this->auth->getUser();
        $finance = Finance::where('user_id', $userId)->find();
        if ($finance->$field < $money) {
            $this->error('余额不足！');
        }

        switch ($remark) {
            case 'person':
                $bankinfo = \app\admin\model\user\Banks::where('type', 1)->where('user_id', $userId)->where('status', 1)->find();
                $accountArr = [
                    '姓名' => $bankinfo->bankholder,
                    '手机号码' => $bankinfo->mobile,
                    '银行名称' => $bankinfo->bankname,
                    '银行卡号' => $bankinfo->banknumber
                ];
                break;
            case 'company':
                $bankinfo = \app\admin\model\user\Banks::where('type', 2)->where('user_id', $userId)->where('status', 2)->find();
                $accountArr = [
                    '姓名' => $bankinfo->bankholder,
                    '手机号码' => $bankinfo->mobile,
                    '银行名称' => $bankinfo->bankname,
                    '银行卡号' => $bankinfo->banknumber
                ];
                break;
            case 'wechat':
                $account = $this->auth->getUser()->wechat_info;
                $accountArr = [
                    '微信号' => $account
                ];
                break;
            case 'alipay':
                $alipay_info = $this->auth->getUser()->alipay_info;
                $alipay_info = json_decode($alipay_info, true);
                $accountArr = [
                    '支付宝账号' => $alipay_info['account'],
                    '姓名' => $alipay_info['name']
                ];
                break;
        }

        $accountInfo = json_encode($accountArr, JSON_UNESCAPED_UNICODE);
        $orderNum = create_order($userId);

        $finance->$field -= $money;
        $odata = [
            'order_num' => $orderNum,
            'user_id' => $userId,
            'money' => $money,
            'hasmoney' => $finance->$field,
            'account_info' => $accountInfo,
            'moneytype' => $moneytype,
            'type' => $remark,
            'status' => 0,
        ];

        Db::startTrans();
        try {
            $finance->save();
            $ret = self::$model->create($odata);
            // 余额流水
//            $before = $user->money + $money;
            $tax_rate = config('site.tax_rate');
            $taxMoney = $money * $tax_rate;
            $orderNum = create_order($user->id);
            $mdata = [
                'order_num' => $orderNum,
                'user_id' => $user->id,
                'record_type' => 0,
                'money' => round($money - $taxMoney, 2),
                'tax_money' => $taxMoney,
                'hasmoney' => $finance->$field,
                'change_type' => 4,// 提现
                'relation_id' => $ret->id,
                'remark' => '申请提现扣减' . $money . $msg
            ];

            Change::create($mdata);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('提现申请失败！');
        }

        $this->success('提现申请成功，等待后台审核！');
    }
}
